import React, { useState } from 'react';
import Empty from '@/components/empty';
import {
  HashRouter as Router,
  Route,
  Switch,
  Redirect
} from 'react-router-dom';
import { routes } from './routes';
import { checkAuth } from '@/utils/auth';
import { RouterLoading } from '@/router/route-config';

// 子路由控制
export const RouteWithSubRoutes = (route) => {
  const [initFlag, setInitFlag] = useState(false);
  const [isError, setIsError] = useState(false);

  const init = async (props) => {
    try {
      const flag = await checkAuth(props);
      setInitFlag(flag);
    } catch (error) {
      setIsError(true);
    }
  };

  return (
    <Route
      path={route.path}
      exact={route.exact}
      render={(props) => {
        if (route.auth && !initFlag) {
          init(props);
          return isError ? (
            <Empty
              isError
              imgUrl={require('@/assets/images/repair.png')}
              text={'网络异常，请稍后刷新重试'}
              reloadText="点击刷新"
              reload={() => window.location.reload()}
            />
          )
            : < RouterLoading />;
        }
        return <route.component {...props} routes={route.routes} />; // 向下传递子路由以保持嵌套
      }}
    />
  );
};

const RouteConfig = () => {
  return (
    <Router>
      <Switch>
        {routes.map((item, i) => (
          <RouteWithSubRoutes key={i} {...item} />
        ))}
        <Redirect to="/home" />
      </Switch>
    </Router>
  );
};

export default RouteConfig;

